/**
 * Copyright (c) 2010 Bob Brady (http://www.bradysoftware.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the 
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 
 * express or implied. See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package com.bradysoftware.rsscenturion;

import java.io.IOException;
import java.net.URL;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherEvent;
import com.sun.syndication.fetcher.FetcherListener;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;

public class CachedFeedTag extends SimpleTagSupport {
	private String url;
	private String feedId;
	private Boolean debug;

	public void setUrl(String url) {
		this.url = url;
	}

	public void setFeedId(String feedId) {
		this.feedId = feedId;
	}
	
	public void setDebug(Boolean debug) {
		this.debug = debug;
	}

	@Override
	public void doTag() throws JspException, IOException {
		try {
			URL feedUrl = new URL(url);
			FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
			FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
			if(debug) {
				FetcherEventListenerImpl listener = new FetcherEventListenerImpl();
				fetcher.addFetcherEventListener(listener);	
			}
			SyndFeed feed = fetcher.retrieveFeed(feedUrl);	
			getJspContext().setAttribute(feedId, feed);
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
	}
	
	static class FetcherEventListenerImpl implements FetcherListener {
		/**
		 * @see com.sun.syndication.fetcher.FetcherListener#fetcherEvent(com.sun.syndication.fetcher.FetcherEvent)
		 */
		public void fetcherEvent(FetcherEvent event) {
			String eventType = event.getEventType();
			if (FetcherEvent.EVENT_TYPE_FEED_POLLED.equals(eventType)) {
				System.err.println("\tEVENT: Feed Polled. URL = " + event.getUrlString());
			} else if (FetcherEvent.EVENT_TYPE_FEED_RETRIEVED.equals(eventType)) {
				System.err.println("\tEVENT: Feed Retrieved. URL = " + event.getUrlString());
			} else if (FetcherEvent.EVENT_TYPE_FEED_UNCHANGED.equals(eventType)) {
				System.err.println("\tEVENT: Feed Unchanged. URL = " + event.getUrlString());
			}
		}
	}


}
